package com.yang.config;

import com.yang.entity.NoteUser;
import com.yang.service.NoteUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Objects;

/**
 * @author yangdacheng
 * @title: MyUserDetailsService
 * @projectName note_api
 * @description: TODO
 * @date 2022/4/9 9:25 上午
 */
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Resource
    private NoteUserService noteUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1、根据用户名称查找用户
        NoteUser noteUser = noteUserService.queryUserByID(username);
        if (Objects.isNull(noteUser)){
            throw new UsernameNotFoundException(username+"没有找到"); //抛出用户不存在异常
        }
        //2、设置用户角色
        Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_"+noteUser.getNoteRole().getRoleName());
        grantedAuthorities.add(grantedAuthority);
        System.out.println("开始设置角色"+grantedAuthority.getAuthority());
        return new User(noteUser.getUsername(),noteUser.getPassword(),grantedAuthorities);
    }
}
